<script setup lang="ts">
import { onMounted, watch, ref } from 'vue';
import logoIcon from '@/assets/images/logo.png'

const emit = defineEmits(['input']);
const globalVal = globalThis as any;
const show = ref(false) //是否显示登录弹窗
const percent = ref(0)
const updateInfo: any = ref(null)
const downloaded = ref(false)

/**
 * 下载更新
 */
function handleDownload(): void {
  console.log('handleDownload')
  globalVal.electronApi.downloadUpdate();
}

function handleInstall(): void {
  show.value = false;
  globalVal.electronApi.quitAndInstall();
}

/**
 * 取消
 */
function cancel(): void {
  show.value = false
}

watch(() => show, (newVal) => {
  emit('input', newVal)
}, {
  immediate: true
})

onMounted(() => {

  if (globalVal.electron) {
    globalVal.electron.ipcRenderer.on('update-available', (event, info) => {
      console.log(event);
      console.log(info)
      updateInfo.value = info
      show.value = true;

    })

    globalVal.electron.ipcRenderer.on('download-progress', ((event, progressInfo: any) => {
      console.log(event)
      percent.value = Math.ceil(progressInfo.percent * 100) / 100
    }));

    globalVal.electron.ipcRenderer.on('update-downloaded', () => {
      globalVal.toast('新版本下载完成, 请重启并安装')
      downloaded.value = true
    })
  }

})


</script>
<template>
  <el-dialog v-model:show="show" title="版本更新" :show-confirm-button="false" width="30rem">
    <img :src="logoIcon" class="logo" />
    <div class="version-info" v-if="updateInfo">发现新版本 {{ updateInfo.version }}，请下载更新!</div>
    <div class="release-description" v-if="updateInfo && updateInfo.releaseNotes">{{ updateInfo.releaseNotes }}</div>
    <el-progress class="progress-bar" :percentage="percent" v-if="percent > 0"></el-progress>
    <div class="dialog-footer">
      <el-button v-if="downloaded" type="primary" @click="handleInstall">重启并安装</el-button>
      <el-button v-else :disabled="percent > 0" type="primary" @click="handleDownload">下载</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.logo {
  width: 80px;
  height: 80px;
  margin: 20px auto;
  display: block;

}

.version-info {
  text-align: center;
}

.release-description {
  padding: 20px 40px;
}

.progress-bar {
  margin: 20px;
}

.dialog-footer {
  margin-top: 80px;
  display: flex;
  border-top: 1px solid #E0E0E0;

  button {
    flex: 1;
    border-radius: 0;
    border: none;
  }
}
</style>
